#include "MsgMatchRequest.h"
#include "Filter.h"
#include "Model.h"
#include "Parser.h"
#include "MsgError.h"
#include "MsgMatchResponse.h"
#include "Tree.h"

using namespace std;

MsgMatchRequest::MsgMatchRequest(const string & data)
{
	size_t szProtocol = data.find_first_of( '\0' );
	string protocol = data.substr(0, szProtocol);
	size_t msgLength = data.length() - szProtocol - 1;
	string message(data.c_str() + (szProtocol + 1), msgLength);
	m_data.protocol = protocol;
	m_data.message = message;
}

POutputMessage MsgMatchRequest::Process(Model * model)
{
	IFilter * filter = model->GetFilter();
	if ( filter == NULL )
	{
		return POutputMessage(new MsgError(ERR_FILTER_NOT_SET, *model, NULL));
	} else {
		try
		{
			Tree * tree = model->GetParser()->Parse(m_data);
			if (tree != NULL)
			{
				bool res = filter->Match(*tree);
				delete tree;
				return POutputMessage(new MsgMatchResponse(res, *model));
			} else {
				return POutputMessage(new MsgError(ERR_UNKNOWN_PROTOCOL, *model, NULL));
			}
		} catch (...)
		{
			return POutputMessage(new MsgError(ERR_INTERNAL_ERROR, *model, NULL));
		}
	}
	return POutputMessage();
}